﻿using System.Collections;
using UnityEngine;
using UnityEditor;
using System.Security.Cryptography;
using System;
using System.IO;
using System.Collections.Generic;

public class ReportWindow : EditorWindow
{ 
    /// <summary> /// 查找重复贴图和模型 /// </summary> 
   [MenuItem("DDZ工具/查找重复贴图和模型")]
    static void ReportTexture() {
        Dictionary<string,string> md5dic = new Dictionary<string, string> ();
        //使用string-string，不用集合，直接判断是否已经有value即可 
        string[] paths = AssetDatabase.FindAssets("t:prefab",new string[]{"Assets/ResourcesAB"});
        //获得的是guid string集合 
        foreach (var prefabGuid in paths)
        {
            string prefabAssetPath = AssetDatabase.GUIDToAssetPath(prefabGuid);
            string[] depend = AssetDatabase.GetDependencies (prefabAssetPath,true);
            for (int i = 0; i < depend.Length; i++)
            {
                string assetPath = depend [i];
                AssetImporter importer = AssetImporter.GetAtPath(assetPath);
                //满足贴图和模型资源 
                if (importer is TextureImporter || importer is ModelImporter)
                {
                    //Audio,视频也是外部导入文件，但一般不加入prefab内存中，资源过大，而是运行中动态加入，material不是外部导入文件，一个角色一般都有一个material 
                    string md5 = GetMD5Hash(Path.Combine(Directory.GetCurrentDirectory(),assetPath));
                    string path;
                    if (!md5dic.TryGetValue (md5, out path))
                    {
                        md5dic [md5] = assetPath;
                    }
                    else
                    {
                        if (path != assetPath)
                        {
                            Debug.LogFormat ("{0} {1} 资源发生重复！被{2}所引用", path, assetPath,prefabAssetPath);
                        }
                    }
                }
            }
        }
    } 
    /// <summary> /// 获取文件Md5 /// </summary> 
    /// <returns>The M d5 hash.</returns> /// 
    /// <param name="filePath">File path.</param> 
    static string GetMD5Hash(string filePath)
    {
        MD5 md5 = new MD5CryptoServiceProvider();
        return BitConverter.ToString(md5.ComputeHash(File.ReadAllBytes(filePath))).Replace("-", "").ToLower();
    }
}
